<template>
	<div>
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>小区管理</el-breadcrumb-item>
		</el-breadcrumb>
		<el-form :inline="true">
			<el-form-item label="小区名称:">
				<el-input v-model="queryInfo.communityName"></el-input>
			</el-form-item>
			<el-form-item label="创建时间:">
				<el-date-picker value-format="yyyy-MM-dd hh:mm:ss" v-model="dataValue" type="daterange" align="right"
					unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
					:picker-options="pickerOptions">
				</el-date-picker>
			</el-form-item>
			<el-form-item>
				<el-button @click="getinfo" type="primary">搜索</el-button>
			</el-form-item><br />


			<el-form-item>
				<el-button :title="title" @click="add" type="primary"> 新增小区</el-button>
				<el-dialog :title="title" :visible.sync="dialogFormVisible" @close="cancle">
					<el-form :model="communityData">
						<el-form-item label="小区名称" label-width="80px" style="margin-top: 10px;">
							<el-input v-model="communityData.communityName"></el-input>
						</el-form-item>
						<el-form-item label="所属地区" label-width="80px" style="margin-top: 10px;">
							<el-cascader v-model="address" :options="citys" @change="handleChange"></el-cascader>
						</el-form-item>
						<el-form-item label-width="80px" style="margin-top: 10px;">
							<el-input placeholder="详细地址" v-model="communityData.communityCoordinates"></el-input>
						</el-form-item>
						<el-form-item label="门店坐标" label-width="80px" style="margin-top: 10px;">
							<el-button @click="getLocation">获取位置</el-button>
							<!--放置经纬度信息-->
							<span
								v-show="show">{{communityData.communityLatitude}},{{communityData.communityLongitude}}</span>
						</el-form-item>
					</el-form>
					<div slot="footer" class="dialog-footer">
						<el-button @click="cancle">取消</el-button>
						<el-button type="primary" @click="updateCommunity">确 定</el-button>
					</div>
				</el-dialog>
			</el-form-item>


		</el-form>
		<el-table :header-cell-style="{fontSize: '14px', backgroundColor: '#1890FF',color:'#ffffff'}" :data="tableData"
			border style="width: 100%">
			<el-table-column prop="communityId" label="ID" width="180">
			</el-table-column>
			<el-table-column prop="communityName" label="名称" width="180">
			</el-table-column>
			<el-table-column prop="communityAddress" label="位置" width="180">
			</el-table-column>
			<el-table-column prop="communityUserCount" label="用户数量" width="180">
			</el-table-column>
			<el-table-column prop="communityShopCount" label="关联门店" width="180">
			</el-table-column>
			<el-table-column prop="createTime" label="创建时间" width="180">
			</el-table-column>
			<el-table-column fixed="right" label="操作" width="100">
				<template slot-scope="scope">
					<el-button @click="handleClick(scope.row.communityId)" type="text" size="small">查看关联门店</el-button>
					<el-button @click="ed(scope.row)" type="text" size="small">编辑小区</el-button>
					 <!-- <el-button  @click="open">点击打开 Message Box</el-button> -->
					<el-button @click="del(scope.row.communityId)" type="text" size="small">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<el-row style="margin-top: 10px;">
			<div class="block">
				<el-pagination layout="prev, pager, next,jumper,total,sizes" @size-change="handleSizeChange"
					@current-change="handleCurrentChange" :current-page="queryInfo.pageNum" :page-sizes="[1,5,10,20]"
					:page-size="queryInfo.pageSize" :total="total">
				</el-pagination>
			</div>
		</el-row>
		<el-dialog title="查看关联门店" :visible.sync="dialogTableVisible">
			<el-row><el-form :inline="true" :model="storesQueryInfo">
			<el-form-item label="门店名称:">
				<el-input v-model="storesQueryInfo.shopName"></el-input>
			</el-form-item>
			<el-form-item label="创建时间:">
				<el-date-picker value-format="yyyy-MM-dd hh:mm:ss" v-model="dataValue" type="daterange" align="right"
					unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
					:picker-options="pickerOptions">
				</el-date-picker>
			</el-form-item>
			<el-form-item>
				<el-button @click="handleClick(communityId)" type="primary">搜索</el-button>
			</el-form-item><br /></el-form></el-row>
		  <el-table :data="storesList">
			<el-table-column prop="shopName" label="名称" width="150"></el-table-column>
			<el-table-column prop="shopId" label="ID" width="150"></el-table-column>
			<el-table-column prop="shopAddress" label="地址" width="150"></el-table-column>
		    <el-table-column prop="shopOrderCount" label="订单数量" width="200"></el-table-column>
		    <el-table-column prop="" label="操作">
				<el-link>删除</el-link>
			</el-table-column>
		  </el-table>
		  <el-row>
			<el-pagination layout="prev, pager, next,jumper,total,sizes" @size-change="handleSizeChange1"
					@current-change="handleCurrentChange1" :current-page="storesQueryInfo.pageNum" :page-sizes="[1,5,10,20]"
					:page-size="queryInfo.pageSize" :total="storeTotal">
				</el-pagination></el-row>
		</el-dialog>
	</div>
</template>

<script>
	import citys from '../assets/citydata.js';
	export default {
		data() {
			return {
				dialogTableVisible:false,
				show: false,
				title: '新增小区',
				address: [],
				communityData: { // 小区信息
					addOrUpdateFlag: 1, // 判断是新增还是修改的标志  1:新增  2：修改
					communityAddress: "", // 小区详细地址
					communityAreaCode: "", // 小区位置编码
					communityCity: "", // 小区所属城市
					communityCoordinates: "", // 小区所属详细地址--
					communityDistrict: "", // 小区所属区域 
					communityId: "", // 小区编号
					communityLatitude: "", // 小区纬度
					communityLongitude: "", // 小区经度
					communityName: "", // 小区名称
					communityProvince: "", // 小区所属省份/直辖市
				},
				citys: citys,
				dialogFormVisible: false,
				total: '',
				tableData: [],
				queryInfo: {
					communityName: '',
					startTime: '',
					endTime: '',
					pageNum: 1,
					pageSize: 10,
					name: ''
				},
				
				storeTotal:1,
				dataValue: [],
				input: '',
				pickerOptions: {
					shortcuts: [{
						text: '最近一周',
						onClick(picker) {
							const end = new Date();
							const start = new Date();
							start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
							picker.$emit('pick', [start, end]);
						}
					}, {
						text: '最近一个月',
						onClick(picker) {
							const end = new Date();
							const start = new Date();
							start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
							picker.$emit('pick', [start, end]);
						}
					}, {
						text: '最近三个月',
						onClick(picker) {
							const end = new Date();
							const start = new Date();
							start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
							picker.$emit('pick', [start, end]);
						}
					}]
				},
				value1: '',
				value2: '',
				storesQueryInfo:{
					pageNum: 1,
					pageSize: 5,
					shopName:'',
					communityId: 1010450 
				},
				storesList:[],
				communityId:''
			}
		},
		methods: {
			handleClick(id) {
			this.communityId=id;
			this.storesQueryInfo.communityId=id;	
			this.$http.get('associatedStores/associatedStoresList', {
			    params: this.storesQueryInfo
			}).then(res => {
			    if (res.data.status === 200) {  // 假设200表示成功
			        this.storesList = res.data.data.list;  // 确保数据路径正确
			        this.storeTotal = res.data.data.total;
			        this.dialogTableVisible = true;
			    } else {
			        this.$message.error('获取门店列表失败');
			    }
			}).catch(error => {
			    console.error('API 请求错误:', error.response ? error.response.data : error.message);
			    this.$message.error('获取数据失败，请检查控制台错误信息');
			});
},
			 open() {
			       
			      },
			cancle() {
				this.dialogFormVisible = false;
				this.address = [];
				this.communityData = { // 小区信息
					addOrUpdateFlag: 1, // 判断是新增还是修改的标志  1:新增  2：修改
					communityAddress: "", // 小区详细地址
					communityAreaCode: "", // 小区位置编码
					communityCity: "", // 小区所属城市
					communityCoordinates: "", // 小区所属详细地址--
					communityDistrict: "", // 小区所属区域 
					communityId: "", // 小区编号
					communityLatitude: "", // 小区纬度
					communityLongitude: "", // 小区经度
					communityName: "", // 小区名称
					communityProvince: "", // 小区所属省份/直辖市
				}


			},
			updateCommunity() {
				this.$http.post('community/communityUpdate', this.communityData)
					.then((res) => {
						if (res.data.status == 200) {
							this.$message.success('添加成功');
							this.dialogFormVisible = false;
							this.getinfo();
						} else {
							this.$message.error('操作失败');
						}
					})
					.catch(error => {
						console.error(error);
						this.$message.error('请求失败，请检查输入信息');
					});
			},
			handleChange() {
				console.log('');
			},
			getLocation() {
				if (!this.communityData.communityDistrict) {
					this.$message.warning('请选择所属地区')
					return
				}
				this.show = true;
				const address = this.communityData.communityProvince +
					this.communityData.communityCity +
					this.communityData.communityDistrict +
					this.communityData.communityAddress;

				this.$http.get('https://restapi.amap.com/v3/geocode/geo', {
					params: {
						key: '457886b5972a97e93fb9cdccebfd450f',
						address: address
					}
				}).then((resp) => {
					if (resp.data.status == '1' && resp.data.geocodes.length > 0) {
						let location = resp.data.geocodes[0].location;
						this.communityData.communityLatitude = location.split(',')[0];
						this.communityData.communityLongitude = location.split(',')[1];
					} else {
						this.$message.error('地址转换失败，请检查地址是否正确');
					}
				}).catch(error => {
					console.error('API 请求错误:', error.response ? error.response.data : error.message);
					this.$message.error('获取位置信息失败，请检查控制台错误信息');
				});
			},
			add() {
				this.dialogFormVisible = true;
			},
		
			ed(row) {
				this.title = "编辑小区";
				this.communityData = row;
				this.dialogFormVisible = true;
				this.communityData.addOrUpdateFlag = 2;
				this.address = [this.communityData.communityProvince, this.communityData.communityCity, this.communityData
					.communityDistrict
				];
			},
			del(communityId) {
				this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
				  confirmButtonText: '确定',
				  cancelButtonText: '取消',
				  type: 'warning'
				}).then(() => {
				  this.$message({
				    type: 'success',
				    message: '删除成功!'
				  });
				}).catch(() => {
				  this.$message({
				    type: 'info',
				    message: '已取消删除'
				  });          
				}).then(
				this.$http.post('community/communityRemove',{'communityId':communityId
		})
				.then((res)=>{
					if(res.data.status==200){
						this.getinfo();
					}
				}))
			},
			handleSizeChange1(val) {
				this.storesQueryInfo.pageSize = val;
				this.storesQueryInfo.pageNum = 1;
				this.handleClick(this.communityId);
			},
			handleSizeChange(val) {
				this.queryInfo.pageSize = val;
				this.queryInfo.pageNum = 1;
				this.getinfo();
			},
			handleCurrentChange(val) {
				this.queryInfo.pageNum = val;
				this.getinfo();
			},
			handleCurrentChange1(val) {
				this.storesQueryInfo.pageNum = val;
				this.handleClick(this.communityId);
			},
			getinfo() {
				console.log(this.dataValue[0])
				console.log(this.dataValue[1])
				this.$http.get('community/communityList', {
						params: this.queryInfo
					})
					.then(res => {
						this.tableData = res.data.data.list;
						this.total = res.data.data.total;
						if (res.data.status == 200) {
							console.log(res.data.data.list)
						} else {
							this.$message.error('服务器接口异常')
						}
					})
			}
		},
		mounted() {
			this.getinfo();
		},
		watch: {
			address() {
				this.communityData.communityProvince = this.address[0];
				this.communityData.communityCity = this.address[1];
				this.communityData.communityDistrict = this.address[2];
			},
			dataValue() {
				if (this.dataValue) {
					this.queryInfo.startTime = this.dataValue[0];
					this.queryInfo.endTime = this.dataValue[1]
				} else {
					this.queryInfo.startTime = '',
						this.queryInfo.endTime = ''
				}
			}
		}
	}
</script>

<style>
</style>